<%@page pageEncoding="UTF-8" isELIgnored="false"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="f" uri="http://www.slim3.org/functions"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="m" uri="http://taglibs.mobylet.org/" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<m:charset/>" />
<c:if test="${empty title}">
<title>なかまちず for mixi</title>
</c:if>
<c:if test="${!empty title}">
<title>${f:h(title)}</title>
</c:if>
<c:import url="/jsp/pc/keyword.jsp"/>
<link rel="stylesheet" type="text/css" href="/css/mixi.css" />
<script type="text/javascript" src="http://maps.google.com/maps?hl=ja&amp;ie=UTF8&amp;file=api&amp;v=2&amp;sensor=false&amp;key=${apiKey}" charset="utf-8"></script>
<script type="text/javascript" src="/js/util.js" charset="utf-8"></script>
<script type="text/javascript" src="/js/gears_init.js" charset="utf-8"></script>
<style type="text/css">
  html { overflow: auto; }
  html, body, td, th { font-family: Arial, sans-serif; margin: 0px; padding: 0px; font-size: 10pt; color: #333333; }
  .text { font-family: Arial, sans-serif; margin: 0px; padding: 0px 10px; height: 100%; font-size: 10pt; color: #333333; }
  #map { position: absolute; top: 30px; left: 10px; width: 600px; height: 450px;}
  #map img { cursor: crosshair; }
  img { border: 0px; }
  form { margin: 0; padding: 0; font-family: Arial, sans-serif; font-size: 10pt; }
  input, textarea { margin: 3px 0 0 0; padding: 0; font-family: Arial, sans-serif; font-size: 10pt; }
  #side_bar { position: absolute; top: 6px; left: 620px; border: 1px solid #666; padding: 5px; line-height: 1.8; overflow:auto; background: url(/icon/white70per.png); width: 150px; height: 462px; }
  #header { background-color: #ffffff; position:absolute; top: 6px; left: 10px; z-index: 99; width: 592px; padding: 2px 4px; overflow: hidden; }
  div.errors { color: red; font-weight: bold; position: absolute; top: 35px; left: 15px; border: 1px solid #666; padding: 0px 5px; overflow:auto; background: url(/icon/white70per.png); width: 300px; height: 60px; }
  #qrcode { background-color: #ffffff; font-size: 10pt; position: absolute; top: 510px; left: 650px; border: 0px solid #666; }
  #body { background-color: #ffffff; font-size: 10pt; position: absolute; top: 485px; left: 10px; border: 1px solid #666; width: 763px; height:116px; padding: 2px 4px; }
  #help { background-color: #ffffff; font-size: 10pt; position: absolute; top: 630px; left: 10px; width: 759px; height: 300px; padding: 2px 4px; border: 3px solid #99b3cc; }
  #copy { font-size: 8pt; position: absolute; top: 490px; left: 650px; }
  #footer { font-size: 8pt; position: absolute; top: 950px; left: 10px; }
  #adsense { font-size: 10pt; position: absolute; top: 6px; left: 790px; }
</style>

<script type="text/javascript">

  function createMarker(point, id, name, comment, timestamp, pcIcon) {
    var opt = new Object();
    var icon = new GIcon();
    var iconUrl = "/icon/" + pcIcon + ".png";
    icon.image = iconUrl;
    icon.iconSize = new GSize(32,37);
    icon.iconAnchor = new GPoint(16,34);
    icon.infoWindowAnchor = new GPoint(25,5);
    icon.clickable = true;
    opt.icon = icon;
    opt.title = name;
    var marker = new GMarker(point, opt);

    var content = "<table><tr><td><b>名前<\/b><\/td><td class='text'>"+name+"<\/td><\/tr><tr><td valign='top'><b>内容<\/b> <\/td><td class='text'>"+nl2br(comment)+"<\/td><\/tr><tr><td><b>日時<\/b> <\/td><td class='text'>"+timestamp+"<\/td><\/tr><\/table><hr width='200px'/>";
    editor[mark_no] = content +
           '<form name="editMemberForm" method="post" onsubmit="return checkout()" action="/mixi/editMember">' +
           '<input type="hidden" name="sid" value="${f:h(sid)}"/>' +
           '<input type="hidden" name="id" value="'+id+'" />' +
           '<table><tr><td>' +
           '名前:&nbsp;<input name="name" type="text" size="16" value="'+name+'"/></td><td>&nbsp;</td></tr>' +
           '<tr><td>編集ﾊﾟｽﾜｰﾄﾞ:&nbsp;<input type="text" name="password" size="7" value=""/></td>' +
           '<td rowspan="3" valign="top"><img src="'+iconUrl+'"/></td></tr><tr><td>' +
           '内容:<br/><textarea name="comment" cols="19" rows="2">'+comment+'</textarea></td></tr>' +
           '<tr><td align="right"><input type="submit" name="cmd" value="編集" /></td></tr></table>' +
           '<\/form><hr width="200px"/>' +
           '<form name="deleteMemberForm" onsubmit="return checkDelete()" method="post" action="/mixi/deleteMember">' +
           '<input type="hidden" name="sid" value="${f:h(sid)}"/>' +
           '<input type="hidden" name="id" value="'+id+'" />' +
           '削除ﾊﾟｽﾜｰﾄﾞ:&nbsp;<input type="text" name="password" size="7"/>&nbsp;<input name="cmd" type="submit" value="削除" />' +
           '<\/form>';
    if(!pcIcon.match(/^landmark\//)){
    	content = content + "<a href='javascript:openMemberEditForm("+mark_no+")'>編集<\/a>";
    }
    //content = content + "<a href='javascript:openEditForm("+mark_no+",\""+pcIcon+"\",\""+id+"\")'>編集<\/a>";
    GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowHtml(content);
    });
    gmarkers[mark_no] = marker;
    side_bar_html += '<a href="javascript:myclick(' +mark_no+ ')"><img src="'+iconUrl+'"/>' + name + '<\/a><br \/>';
    mark_no++;
    return marker;
  }
  function openMemberEditForm(i) {
    gmarkers[i].openInfoWindowHtml(editor[i]);
  }
  function myclick(i) {
    GEvent.trigger(gmarkers[i], "click");
  }
  function setIconImage(iconName){
  	if(iconName){
  		var iconUrl = "/icon/"+iconName+".png";
  		document.getElementById('iconImageSample').innerHTML="<img src='"+iconUrl+"' style='float: left;'/>";
  	}else{
  		document.getElementById('iconImageSample').innerHTML="";
  	}
  }
  function editIconImage(iconName, id){
  	var elementId = "iconSample" + id;
  	if(iconName){
  		var iconUrl = "/icon/"+iconName+".png";
  		document.getElementById(elementId).innerHTML="<img src='"+iconUrl+"' style='float: left;'/>";
  	}else{
  		document.getElementById(elementId).innerHTML="";
  	}
  }
  function addMarker(markers, bounds){
  	if(!bounds){
  		bounds = new GLatLngBounds();
  	}
	for (var i = 0; i < markers.length; i++) {
		var lats = markers[i].getElementsByTagName("lat");
		var lngs = markers[i].getElementsByTagName("lng");
		var point = new GLatLng(parseFloat(GXml.value(lats[0])), parseFloat(GXml.value(lngs[0])));
		var ids = markers[i].getElementsByTagName("id");
		var id = GXml.value(ids[0]);
		var names = markers[i].getElementsByTagName("name");
		var name = GXml.value(names[0]);
		var comments = markers[i].getElementsByTagName("comment");
		var comment = GXml.value(comments[0]);
		var timestamps = markers[i].getElementsByTagName("timestamp");
		var timestamp = GXml.value(timestamps[0]);
		var ips = markers[i].getElementsByTagName("ip");
		var ip = GXml.value(ips[0]);
		var pcIcons = markers[i].getElementsByTagName("pcIcon");
		var pcIcon = GXml.value(pcIcons[0]);
		var marker = createMarker(point, id, name, comment, timestamp, pcIcon);
		map.addOverlay(marker);
		bounds.extend(point);
	}
	return bounds;
  }
  
  function addRoute(lines, isWalking){
  	
  	var preGuid = "";
  	var pointArray = new Array();
  	var tr_mode = G_TRAVEL_MODE_DRIVING; // G_TRAVEL_MODE_WALKING;
  	if(isWalking){
  		tr_mode = G_TRAVEL_MODE_WALKING;
  	}
  	var opts = {locale: 'ja_JP',
  				travelMode: tr_mode,
  				avoidHighways: false};
  	var endPoint = new GLatLng(0.0, 0.0);
  	for (var i = 0; i < lines.length; i++) {
  		var slats = lines[i].getElementsByTagName("startLat");
  		var slngs = lines[i].getElementsByTagName("startLng");
  		var elats = lines[i].getElementsByTagName("endLat");
  		var elngs = lines[i].getElementsByTagName("endLng");
  		var guids = lines[i].getElementsByTagName("guid");
 		var sp = new GLatLng(parseFloat(GXml.value(slats[0])), parseFloat(GXml.value(slngs[0])));
  		var ep = new GLatLng(parseFloat(GXml.value(elats[0])), parseFloat(GXml.value(elngs[0])));
  		var guid = GXml.value(guids[0]);
  		if(guid != preGuid || !endPoint.equals(sp) || pointArray.length > 24){
  			//alert(pointArray.length);
  			preGuid = guid;
  			if(pointArray.length > 0){
  				var directions = new GDirections(map);
  				directions.loadFromWaypoints(copyArray(pointArray), opts);
  				pointArray = new Array();
  			}

  			pointArray.push(sp);
  			pointArray.push(ep);
  			endPoint = ep;
  		}else{
  			if(endPoint.equals(sp)){
  				pointArray.push(ep);
  			}else{
  				pointArray.push(sp);
  				pointArray.push(ep);
  			}
  			endPoint = ep;
  		}

  	}
  	if(pointArray.length > 0){
		var directions = new GDirections(map);
		directions.loadFromWaypoints(copyArray(pointArray), opts);
		pointArray = new Array();
  	}
  }
  
  function addLine(lines){
  	
  	var preGuid = "";
  	var pointArray = new Array();
  	var color = "#ff0000";
  	// G_TRAVEL_MODE_WALKING
  	var opts = {locale: 'ja_JP',
  				travelMode: G_TRAVEL_MODE_DRIVING,
  				avoidHighways: false};
  	var endPoint = new GLatLng(0.0, 0.0);
  	for (var i = 0; i < lines.length; i++) {
  		var slats = lines[i].getElementsByTagName("startLat");
  		var slngs = lines[i].getElementsByTagName("startLng");
  		var elats = lines[i].getElementsByTagName("endLat");
  		var elngs = lines[i].getElementsByTagName("endLng");
  		var guids = lines[i].getElementsByTagName("guid");
  		var colors = lines[i].getElementsByTagName("color");
 		var sp = new GLatLng(parseFloat(GXml.value(slats[0])), parseFloat(GXml.value(slngs[0])));
  		var ep = new GLatLng(parseFloat(GXml.value(elats[0])), parseFloat(GXml.value(elngs[0])));
  		var guid = GXml.value(guids[0]);
  		color = GXml.value(colors[0]);
  		if(guid != preGuid || !endPoint.equals(sp)){
  			//alert(pointArray.length);
  			preGuid = guid;
  			if(pointArray.length > 0){
  				var polyline = new GPolyline(copyArray(pointArray), color, 3);
  				map.addOverlay(polyline);
  				pointArray = new Array();
  			}

  			pointArray.push(sp);
  			pointArray.push(ep);
  			endPoint = ep;
  		}else{
  			if(endPoint.equals(sp)){
  				pointArray.push(ep);
  			}else{
  				pointArray.push(sp);
  				pointArray.push(ep);
  			}
  			endPoint = ep;
  		}

  	}
  	if(pointArray.length > 0){
		var polyline = new GPolyline(copyArray(pointArray), color, 5);
		map.addOverlay(polyline);
		pointArray = new Array();
  	}
  }
  
  function copyArray(arr){
  	var tmp = new Array(arr.length);
  	for(var i=0;i<arr.length;i++){
  		tmp[i] = arr[i];
  	}
  	return tmp;
  }
  


  function check() {
    if (document.addMemberForm.name.value == "") {
      alert("名前を入力してください。");
	  document.addMemberForm.name.focus();
	  return false;
	}
	if (document.addMemberForm.name.value.length > 10) {
	  alert("名前を10文字以内で入力してください。");
	  document.addMemberForm.name.focus();
	  return false;
	}
	if (document.addMemberForm.comment.value == "") {
	  alert("内容を入力してください。");
	  document.addMemberForm.comment.focus();
	  return false;
	}
	if (document.addMemberForm.comment.value.length > 100) {
	  alert("内容を100文字以内で入力してください。");
	  document.addMemberForm.comment.focus();
	  return false;
	}
	if (document.addMemberForm.password.value == "") {
	  alert("パスワードを入力してください。");
	  document.addMemberForm.password.focus();
	  return false;
	}
	if (document.addMemberForm.password.value.length > 16) {
	  alert("パスワードを16文字以内で入力してください。");
	  document.addMemberForm.password.focus();
	  return false;
	}

	return true;
  }


function checkout() {
  if (document.editMemberForm.name.value == "") {
    alert("名前を入力してください。");
    document.editMemberForm.name.focus();
    return false;
  }
  if (document.editMemberForm.name.value.length > 10) {
    alert("名前を10文字以内で入力してください。");
    document.editMemberForm.name.focus();
    return false;
  }
  if (document.editMemberForm.comment.value == "") {
    alert("内容を入力してください。");
    document.editMemberForm.comment.focus();
    return false;
  }
  if (document.editMemberForm.comment.value.length > 100) {
    alert("内容を100文字以内で入力してください。");
    document.editMemberForm.comment.focus();
    return false;
  }
  if (document.editMemberForm.password.value == "") {
    alert("編集パスワードを入力してください。");
    document.editMemberForm.password.focus();
    return false;
  }
  return true;
}

function checkDelete(){
  if (document.deleteMemberForm.password.value == "") {
    alert("削除パスワードを入力してください。");
    document.deleteMemberForm.name.focus();
    return false;
  }

}

function htmlEscape(str){
  var div = document.createElement('div');
  var text =  document.createTextNode('');
  div.appendChild(text);
  text.data = str;
  return div.innerHTML;
}

function nl2br(str){
  str = str.replace(/\r\n/g, "\n");
  str = str.replace(/\r/g, "\n");
  str = str.replace(/\n/g, '<br>');
  str = str.replace(/(<br>)+/g, '<br/>');
  return str;
}

function getCurrentPosition(){
	if(navigator.userAgent.indexOf("MSIE") == -1){
		navigator.geolocation.getCurrentPosition(positionSuccess, getClientPosition);
	}else{
		if(!window.google || !google.gears){
			location.href = "http://gears.google.com/?action=install&message=nakamachizu%20required%20Google%20Gears." + "&return=http://${f:h(serverName)}/map?key=${f:h(mapKey)}";

		}else{
			google.gears.factory.create('beta.geolocation').getCurrentPosition(positionSuccess, getClientPosition);
		}
	}
}

function positionSuccess(pos){
	makeSelfMarker(pos.coords.latitude, pos.coords.longitude);
	//alert(pos.coords.latitude + ' : ' + pos.coords.longitude);
}

function getClientPosition(error){
	var cl = google.loader.ClientLocation;
	if(cl){
		makeSelfMarker(cl.latitude, cl.longitude);
		//alert(cl.latitude + ' : ' + cl.longitude);
	}else{
		positionError(error);
	}
	
}

function makeSelfMarker(lat, lng){
	var latlng = new GLatLng(lat, lng);
	markera.setLatLng(latlng);
	markera.show();
	GEvent.addListener(markera, "click", function() {
		var latlng = markera.getLatLng();
		var lat = latlng.lat();
		var lng = latlng.lng();
		var html = "<form name='addMemberForm' method='post' onsubmit='return check()' action='/mixi/addMember'><input type='hidden' name='sid' value='${f:h(sid)}'/><input type='hidden' name='lat' value='"+lat+"'/><input type='hidden' name='lng' value='"+lng+"'/><table><tr><td><b>名前:<\/b>&nbsp;<input name='name' type='text' size='16'\/><\/td><td>&nbsp;<\/td><\/tr><tr><td><b>編集ﾊﾟｽﾜｰﾄﾞ:<\/b>&nbsp;<input name='password' type='password' size='7'\/><\/td><\/tr><tr><td><b>内容:<\/b><br\/><textarea name='comment' cols='19' rows='2' wrap='VIRTUAL'><\/textarea><\/td><\/tr><tr><td><div align='right'><input type='hidden' name='key' value='"+mapId+"'\/><input type='submit' value='追加'\/><\/div><\/td><\/tr><\/table><\/form>";
		markera.openInfoWindow(html);
	});
	map.setCenter(latlng, 17);
}

function positionError(error){
	alert("位置情報の取得に失敗しました。 ERROR_CODE: " + error.code);
}
</script>
</head>
<body onunload="GUnload()">
<!-- 
http://maps.google.co.jp/maps?hl=ja&ie=UTF8&ll=${f:h(cLat)},${f:h(cLng)}&spn=0.008581,0.020792&z=16&brcurrent=3,0x60185c0dece046d9:0xbd199dace57b6af,1
 -->
<div id="map">Loading...</div>

<div id="side_bar">Loading...</div>
<div id="header"><c:if test="${empty title}">「なかまちず」</c:if><c:if test="${!empty title}">「${f:h(title)}」</c:if>クリックで新しいポイントを追加できます。</div>

<div id="body"><!-- start body -->
<table>
 <tr>
  <td>
<h2>有効期限:</h2>
<p class="indent"><fmt:formatDate value="${expire}" pattern="yyyy/MM/dd HH:mm:ss"/></p>
  </td>
  <td>
<h2>位置情報送信</h2>
<p class="indent"><button type="button" onClick="getCurrentPosition();">位置情報を送信する</button></p>
  </td>
  <td>
<h2>公開設定</h2>
<p class="indent">
<c:if test="${accessLevel == 1}">全公開</c:if>
<c:if test="${accessLevel == 2}">友達まで公開(外部からは許可)</c:if>
<c:if test="${accessLevel == 3}">友達まで公開(外部からも拒否)</c:if>
</p>
  </td>
 </tr>
 <tr>
  <td colspan="3">
<h2>外部アクセスURL</h2>
<p class="indent"><a href="/mixi/jump?url=http%3a%2f%2f${serverName}%2fmap%3fkey%3d${f:h(mapKey)}">http://${serverName}/map?key=${f:h(mapKey)}</a></p>
  </td>
 </tr>
</table>

<p>※QRコードは外部アクセス用のURLです。mixiのコンテンツやサービスではありません。</p>

</div><!-- end body -->

<div id="copy">&copy; nakamachizu.com</div>
<div id="qrcode"><img src="http://chart.apis.google.com/chart?chs=90x90&cht=qr&chl=%E3%81%AA%E3%81%8B%E3%81%BE%E3%81%A1%E3%81%9A%0D%0Ahttp%3A%2F%2F${serverName}%2Fmap%3Fkey%3D${mapKey}%0d%0a%0d%0a%e2%80%bb%e3%83%aa%e3%83%b3%e3%82%af%e5%85%88%e3%81%af%e3%80%81mixi%e3%81%ae%e3%82%b3%e3%83%b3%e3%83%86%e3%83%b3%e3%83%84%e3%82%84%e3%82%b5%e3%83%bc%e3%83%93%e3%82%b9%e3%81%a7%e3%81%af%e3%81%82%e3%82%8a%e3%81%be%e3%81%9b%e3%82%93%e3%80%82&chld=L|1&choe=Shift_JIS"/></div>

<c:if test="${!empty errors}">
<div class="errors">
<ul type="disc">
<c:forEach var="e" items="${f:errors()}">
<li>${f:h(e)}</li>
</c:forEach>
</ul>
</div>
</c:if>

<script type="text/javascript">
//<![CDATA[
var icon1;
if(!icon1){
	icon1 = new GIcon();
	icon1.image = "http://www.google.com/mapfiles/gadget/markerSmall80.png";
	icon1.shadow = "http://www.google.com/mapfiles/gadget/shadow50Small80.png";
	icon1.iconSize = new GSize(16, 27);
	icon1.shadowSize = new GSize(31, 27);
	icon1.iconAnchor = new GPoint(8, 27);
	icon1.infoWindowAnchor = new GPoint(8, 1);
}
if (GBrowserIsCompatible()) {
  var side_bar_html = "";
  var gmarkers = [];
  var memMarkers = [];
  var mark_no = 0;
  var editor = [];
  var map = new GMap2(document.getElementById("map"));
  var mapId;
  map.setUIToDefault();
  map.addControl(new GNavLabelControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(8, 29)));
  map.removeMapType(G_HYBRID_MAP);

  var markera;
  if(!markera){
  	markera = new GMarker(new GLatLng(0,0), {icon:icon1, draggable:true, hide:true});
  	map.addOverlay(markera);
  }

//  map.setCenter(new GLatLng(35.6810976,139.7671169), 13);
  GDownloadUrl("/mixi/xml?sid=${f:h(sid)}&"+Math.random(), function(data, responseCode) {
    if(responseCode == 200) {
      var xml = GXml.parse(data);
      var keys = xml.documentElement.getElementsByTagName("key");
      mapId = GXml.value(keys[0]);
      var members = xml.documentElement.getElementsByTagName("member");
      var bounds = addMarker(members, null);
      var landmarks = xml.documentElement.getElementsByTagName("landmark");
      bounds = addMarker(landmarks, bounds);
      var lineTypes = xml.documentElement.getElementsByTagName("lineType");
      var lineType = GXml.value(lineTypes[0]);
      var lines = xml.documentElement.getElementsByTagName("line");
      if(lineType == "2"){
      	addRoute(lines, false);
      }else if(lineType == "3"){
      	addRoute(lines, true);
      }else{
      	addLine(lines);
      }
      if(landmarks.length > 0 || members.length > 0){
      	map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
      }else{
      	map.setCenter(new GLatLng(35.6810976,139.7671169), 13);
      }
      document.getElementById("side_bar").innerHTML = side_bar_html;
    } else if (responseCode == -1) {
      alert("Data request timed out. Please try later.");
    } else {
      alert("IOException. Check XML file.");
    }
  });
  GEvent.addListener(map, "click", function(overlay, latlng) {
    if (latlng) {
      <%-- markera = new GMarker(latlng, {icon: icon1, draggable:true});  --%>
      markera.setLatLng(latlng);
      markera.show();
      GEvent.addListener(markera, "click", function() {
        var latlng = markera.getLatLng();
        var lat = latlng.lat();
        var lng = latlng.lng();
		var html = "<form name='addMemberForm' method='post' onsubmit='return check()' action='/mixi/addMember'><input type='hidden' name='sid' value='${f:h(sid)}'/><input type='hidden' name='lat' value='"+lat+"'/><input type='hidden' name='lng' value='"+lng+"'/><table><tr><td><b>名前:<\/b>&nbsp;<input name='name' type='text' size='16'\/><\/td><td>&nbsp;<\/td><\/tr><tr><td><b>編集ﾊﾟｽﾜｰﾄﾞ:<\/b>&nbsp;<input name='password' type='password' size='7'\/><\/td><\/tr><tr><td><b>内容:<\/b><br\/><textarea name='comment' cols='19' rows='2' wrap='VIRTUAL'><\/textarea><\/td><\/tr><tr><td><div align='right'><input type='hidden' name='key' value='"+mapId+"'\/><input type='submit' value='追加'\/><\/div><\/td><\/tr><\/table><\/form>";
        markera.openInfoWindow(html);
      });
      //map.addOverlay(markera);
    }
  });
  
}

<c:if test="${!empty errors}">
var err = "";
<c:forEach var="e" items="${f:errors()}">
err += "${f:h(e)}\n";
</c:forEach>
alert(err);
</c:if>


<c:if test="${!empty messages}">
var msg = "";
<c:forEach var="m" items="${messages}">
msg += "${f:h(m)}\n";
</c:forEach>
alert(msg);
</c:if>


//]]>
</script>




</body>
</html>